/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.xmlbeans.impl.jam.xml.TunnelledException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainSignCalendar;
import org.springblade.modules.admin.vo.UserReportConfigListVO;
import org.springblade.modules.admin.vo.sign.SignWorkforceAddVo;
import org.springblade.modules.admin.vo.sign.SignWorkforceUserVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.UserWorkforceSign;
import org.springblade.modules.admin.vo.UserWorkforceSignVO;
import org.springblade.modules.admin.wrapper.UserWorkforceSignWrapper;
import org.springblade.modules.admin.service.IUserWorkforceSignService;
import org.springblade.core.boot.ctrl.BladeController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户考勤排班计划表 控制器
 *
 * @author ysq
 * @since 2024-10-09
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/user/workforce/sign")
@Api(value = "用户考勤排班计划表", tags = "用户考勤排班计划表接口")
public class UserWorkforceSignController extends BladeController {

	private final IUserWorkforceSignService userWorkforceSignService;


	@PostMapping("batch/add")
	@ApiOperation("快捷值班")
	public R<Boolean> batchAdd(@RequestBody List<SignWorkforceAddVo> signWorkforceAddVos) {
		userWorkforceSignService.batchAdd(signWorkforceAddVos);
		return R.data(true);
	}


	/**
	 * 删除值班
	 * 组id和人员id二选一
	 *
	 * @param groupIds 组id
	 * @param userId   人员id
	 * @param date     日期
	 * @return 数据集
	 */
	@GetMapping("remove")
	@ApiOperation("删除值班")
	public R<Boolean> add(String groupIds, Long userId, Date date) {
		Integer yyyyMMdd = Convert.toInt(DateUtil.format(date, "yyyyMMdd"));
		userWorkforceSignService.remove(Wrappers.<UserWorkforceSign>lambdaQuery().eq(UserWorkforceSign::getUserId, userId).eq(UserWorkforceSign::getSignDate, yyyyMMdd));
		return R.data(true);
	}


	@PostMapping("add")
	@ApiOperation("小组值班")
	public R<Boolean> batchAdd(@RequestBody SignWorkforceAddVo signWorkforceAddVos) {
		userWorkforceSignService.add(signWorkforceAddVos);
		return R.data(true);
	}


	@PostMapping("date/list")
	@ApiOperation("考勤日历")
	public R<List<MaintainSignCalendar>> signDateList(@RequestBody SignWorkforceAddVo signWorkforceAddVo) {
		List<MaintainSignCalendar> list = userWorkforceSignService.signDateList(signWorkforceAddVo);
		return R.data(list);
	}


	/**
	 * 小组值班列表
	 *
	 * @param date    查询日期
	 * @param holiday 类型 0: 工作日，1: 休息日
	 * @return 数据集
	 */
	@GetMapping("list/group")
	@ApiOperation("小组值班列表")
	public R<List<SignWorkforceUserVo>> listGroup(Date date, Integer holiday) {
		List<SignWorkforceUserVo> list = userWorkforceSignService.groupList(date, holiday);
		return R.data(list);
	}


	@PostMapping("list/group/detail")
	@ApiOperation("小组值班列表明细")
	public R<IPage<UserReportConfigListVO>> listGroupDetail(@RequestBody SignWorkforceAddVo signWorkforceAddVo) {
		Query query = new Query();
		query.setSize(signWorkforceAddVo.getSize());
		query.setCurrent(signWorkforceAddVo.getCurrent());
		IPage<UserReportConfigListVO> page = Condition.getPage(query);
		List<UserReportConfigListVO> list = userWorkforceSignService.listDetail(page, signWorkforceAddVo);
		page.setRecords(list);
		return R.data(page);
	}

	/**
	 * 发送值班计划通知
	 *
	 * @return
	 */
	@PostMapping("send/message")
	@ApiOperation("发送值班计划通知")
	public R<Boolean> sendMessage(@RequestBody SignWorkforceAddVo signWorkforceAddVo) {
		userWorkforceSignService.sendMessage(signWorkforceAddVo);
		return R.data(true);
	}



	@PostMapping("sign/user/list")
	@ApiOperation("获取所有考勤人员")
	public R<List<SignWorkforceUserVo>> getSignUserList(@RequestBody SignWorkforceAddVo signWorkforceAddVo){
			return R.data(userWorkforceSignService.getSignUserList(signWorkforceAddVo));
	}

	/**
	 * 小组值班下载
	 *
	 * @param signWorkforceAddVo 查询条件
	 * @return 数据集
	 */
	@PostMapping("list/down/excel")
	@ApiOperation("小组值班列表下载")
	public void downExcel(HttpServletResponse response, @RequestBody SignWorkforceAddVo signWorkforceAddVo) throws IOException {
		List<List<String>> rows = userWorkforceSignService.listExcel(signWorkforceAddVo.getBeginDate(), signWorkforceAddVo.getEndDate());
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (
			Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}



	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
